<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Grouppurchase extends CI_Controller 
{

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */

	public function __construct()
	{
		parent::__construct();

		$this->load->helper('url');
		$this->load->helper('form');
		$this->load->model('group_model');
		$this->load->model('user_model');
		$this->load->database();
	}

	public function get_user_id()
	{
		$user_id = $this->input->get('userid', TRUE);
		
		if ($user_id == "" or $user_id==null)
		{
			// Get history user info by session
			$user_id = $this->session->userdata('user_id');
			
			if ($user_id == False)
			{
				$this->load->view('tips/loginfail');
			}
		}
		$query = $this->user_model->get_user($user_id);
		if($query == null)
		{
			$data = array(
      			'user_id' => $user_id,
    		);
    		$this->db->insert('user', $data); 
		}
		return $user_id;	
	}

	// 团购列表页面
	// 返回：把有效期之内的所有团购（团购名称、logo的地址、简要介绍、团购ID）
	public function index()
	{
		$data["user_id"] = $this->get_user_id();
		$data["groups"] = $this->group_model->get_avaGroups();
		$this->load->view('grouppurchase/grouplist', $data); // 返回
	}


	// 团购详情
	public function groupdetail()
	{
		$data["user_id"] = $this->get_user_id();
		$group_id = $this->input->get("group_id", TRUE);
		$data['group_id'] = $group_id;
		if (!$this->chargeID($group_id,2))
		{
			$data['title'] = '查看团购详情';
			$data['reason'] = "您的group_id不合法，请检查连接或返回重新操作。";
			$this->load->view('grouppurchase/fail', $data);
		}
		else
		{
			// 从数据库拿到该店铺的所有信息以及图片地址
			$result = $this->group_model->get_group($group_id);
			// 判断是否为空
			if($result != null)
			{
				$data["group_detail"] = $result;// 店铺本身信息
				$data["group_pics"] = $this->group_model->get_pics($group_id);// 店铺图片信息
				$data["isAva"] = True;
				// 是否过期
				$data["isOutOfDate"] = False;
				if(time() >= strtotime($result['buy_deadline']))
				{
					$data["isOutOfDate"] = True;
					$data["isAva"] = False;
				}

				// 是否已售完
				$data["isSoldOut"] = False;
				if ($result["buy_num"] >= $result["group_capacity"] or $result["user_num"] >= $result["user_capacity"])
				{
					$data["isSoldOut"] = True;
					$data["isAva"] = False;
				}

				// 如果被删除或成为历史单
				if ($result["group_state"] > 3){
					$data["isAva"] = False;
				}

				// 返回到view
				$this->load->view('grouppurchase/groupdetail', $data);
			}
			else
			{
				$data['title'] = '查看团购详情';
				$data["reason"] = "不存在该团购！请检查连接或返回重新操作。";
				$this->load->view('grouppurchase/fail', $data);
			}
		}
	}

	// 用户在团购详情页，点击“下单”
	// 返回：
	public function createGroupBill()
	{
		// 传入group_id与user_id,判断信息正确性
		$user_id = $this->get_user_id();
		$data["user_id"] = $user_id;
		$group_id = $this->input->get("group_id", TRUE);
		$data["group_id"] = $group_id;
		if (!$this->chargeID($group_id,2))
		{
			$data['title'] = '下单';
			$data['reason'] = "您的group_id不合法，请检查连接或返回重新操作。";
			$this->load->view('grouppurchase/fail', $data);
			return;
		}
		//判断是否返回值为空
		$result = $this->group_model->get_group($group_id);//团购名称与单价
		if($result != null)
		{
			if(time() >= strtotime($result['buy_deadline']))
			{
				$data['title'] = '订购';
				$data["reason"] = "团购已过期！请返回选择其他团购。";
				$this->load->view('grouppurchase/fail', $data);
				return;
			}
			if($result['buy_num'] >= $result['group_capacity'])
			{
				$data['title'] = '订购';
				$data["reason"] = "已售完！请返回选择其他团购。";
				$this->load->view('grouppurchase/fail', $data);
				return;
			}
			else if($result['group_capacity']-$result['buy_num'] < $result['per_user_num'] )
			{
				$result['per_user_num'] = $result['group_capacity']-$result['buy_num'];
			}
			$user_bills_num = $this->group_model->get_bills_num($user_id,$group_id);
			if($user_bills_num >= $result['per_user_capacity'])
			{
				$data['title'] = '订购';
				$data["reason"] = "本团购每人仅限购".$result['per_user_capacity']."份,您已购买" . $user_bills_num . "份。";
				$this->load->view('grouppurchase/fail', $data);
				return;
			}
			else if($result['per_user_capacity']-$user_bills_num < $result['per_user_num'] )
			{
				$result['per_user_num'] = $result['per_user_capacity']-$user_bills_num;
			}
			$data["group_detail"] = $result;
			$data['user_info'] = $this->user_model->get_user($user_id);//用户历史姓名、手机、邮箱
			$this->load->view('grouppurchase/grouppay', $data);
		}
		else
		{
				$data['title'] = '下单';
				$data["reason"] = "不存在该团购！请检查连接或返回重新操作。";
				$this->load->view('grouppurchase/fail', $data);
		}
	}

	// 用户最终提交订单
	public function newGroupBill()
	{
		if ($_POST == False)
		{
			redirect(site_url("grouppurchase"));
		}

	    $user_id = $this->get_user_id();
	    $group_id = $this->input->post("group_id");
	    if (!$this->chargeID($group_id,2))
		{
			$data['title'] = '下单';
			$data['reason'] = "您的group_id不合法，请检查连接或返回重新操作。";
			$this->load->view('grouppurchase/fail', $data);
			return;
		}
		$group_key = $this->generate_key();
	    $result = $this->group_model->new_group_bill($user_id,$group_key);
	    
		// TODO 判断是否为空
		
		// 店铺本身信息
	    if( $result['info'] == 3)//下单成功
	    {
	    	$data["group_detail"] = $result['group_detail'];
	    	$data['user_id'] = $user_id;
	    	$data['group_bill_id'] = $result['bill_id'];
	    	$data['bill_key'] = strval($data['group_bill_id']) . $group_key;
		    $data['group_id'] = $group_id;
			$data['amount'] = $this->input->post("groupnum");
			$data['user_name'] = $this->input->post("name");
			$data['user_mail'] = $this->input->post("mail");
			$data['user_phone'] = $this->input->post("phone");
			$data['bill_note'] = $this->input->post("note");
	    	$data['title'] = '下单成功';
	    	$this->success($data);// 返回成功页面
	    }
	    else 
	    {
	    	$data['title'] = '下单';
	    	$this->failed($data,$result['info']);
	    }

	}

	public function success($data)
	{
		// 返回
	    $this->load->view('grouppurchase/success', $data);
	}

	public function failed($data,$info=-1)
	{	
		// 返回
		if( $info == 0)//由于信息不全导致的下单失败
	    {
	        $data['reason'] = "您填写的信息不完整";
	    }
	    else if ($info == 1)//重复下单导致的下单失败
	    {
	    	$data['reason'] = "您在短时间内重复下单";
	    }
	    else if ($info == 2)//重复下单导致的下单失败
	    {
	    	$data['reason'] = "数据库连接出错，请重新下单";
	    }
	    else if ($info == 4)//重复下单导致的下单失败
	    {
	    	$data["reason"] = "不存在该团购！请检查连接或返回重新操作。";
	    }
	    else if ($info == 5)//重复下单导致的下单失败
	    {
	    	$data["reason"] = "购买数量超出限额！请检查连接或返回重新操作。";
	    }
	    else if ($info == 6)//重复下单导致的下单失败
	    {
	    	$data["reason"] = "购买数量超出每人限购数量！";
	    }
	    $this->load->view('grouppurchase/fail', $data);
	}

	// 显示历史列表
	public function history()
	{
		// 传入
		$user_id = $this->get_user_id();
		$data['user_id'] = $user_id;
		$page_num = $this->input->get("page_num");
		if ($page_num == "")
		{
			$page_num = 1;
		}
		$page_limit = 8;
		// 返回相应范围内的团购列表
		//	每个团购包括：
		//		* group_bill_id
		//		* logo, 团购名称
		//		* 下单时间,
		$data['history_bills'] = $this->group_model->get_group_history($user_id,$page_num,$page_limit);
		$data['total_rows'] = $this->group_model->count_group_history($user_id);
		$data['per_page'] = $page_limit;
		// 返回userid
		$this->load->view('grouppurchase/grouphistory',$data);

	}

	// 显示订单的详细内容
	public function historyBill()
	{
		// 传入: group_bill_id, userid
		$user_id = $this->get_user_id();
		$group_bill_id = $this->input->get("group_bill_id", TRUE);
		if (!$this->chargeID($group_bill_id,3))
		{
			$data['title'] = '查看订单';
			$data['reason'] = "您的订单id不合法，请检查连接或返回重新操作。";
			$data['backurl'] = "grouppurchase/history";
			$this->load->view('grouppurchase/fail', $data);
			return;
		}
		$result = $this->group_model->get_bill($group_bill_id,$user_id);
		if($result != null)
		{
			$data["user_id"] = $user_id;
			$data["group_bill_id"] = $group_bill_id;
			$data['group_detail'] = $result;
			$this->load->view("grouppurchase/grouphistorydetail", $data);
		}
		else
		{
			$data['title'] = '查看订单';
			$data["reason"] = "不存在该订单！请检查连接或返回重新操作。";
			$data['backurl'] = "grouppurchase/history";
			$this->load->view('grouppurchase/fail', $data);
		}
				
	}


	public function send2mail($mail, $title = "新订单", $content = "")
	{
		$config['protocol'] = 'smtp';
		$config['charset'] = 'utf-8';
		$config['wordwrap'] = TRUE;
		$config['smtp_host'] = 'smtp.163.com';
		$config['smtp_user'] = 'juhuijiainfo@163.com';
		$config['smtp_pass'] = 'juhuijiainfo123';

		$this->load->library('email');

		$this->email->initialize($config);


		$this->email->from('juhuijiainfo@163.com', '刘晓宁');
		$this->email->to('juhuijiainfo@163.com,' . $mail); 

		$this->email->subject($title);
		$this->email->message($content); 

		$this->email->send();

		//echo $this->email->print_debugger();
	}

	public function generate_key( $length = 8 ) 
  	{
    	// 密码字符集，可任意添加你需要的字符
    	$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    	$group_key = '';
    	for ( $i = 0; $i < $length; $i++ ) 
    	{
      		$group_key .= $chars[ mt_rand(0, strlen($chars) - 1) ];
    	}
    	return $group_key;
  	}

  	public function chargeID($id,$type) //type:1 for user_id, 2 for group_id
  	{
  		if($type==1)
  		{
  			if($id=="")
  				return false;
  			else
  				return true;
  		}

  		if($type==2)
  		{
  			$length = strlen($id);
  			for($i=0;$i<$length;$i++)
  			{
  				if(!($id[$i]<='9' and $id[$i]>='0'))
  					return false;
  			}
  			return true;
  		}

  		if($type==3)
  		{
  			$length = strlen($id);
  			for($i=0;$i<$length;$i++)
  			{
  				if(!($id[$i]<='9' and $id[$i]>='0'))
  					return false;
  			}
  			return true;
  		}
  	}
}

/* End of file grouppurchase.php */
/* Location: ./application/controllers/grouppurchase.php */